package com.cwnu.sw.cys.core.common.event.listener;

import com.cwnu.sw.cys.core.common.event.UserBlackEvent;
import com.cwnu.sw.cys.core.user.dao.UserDao;
import com.cwnu.sw.cys.core.user.service.cache.UserCache;
import com.cwnu.sw.cys.core.websocket.service.WebSocketService;
import com.cwnu.sw.cys.core.websocket.service.adapter.WebSocketBuilder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

/**
 * 用户拉黑监听器
 *
 * @author jisam
 * @version 1.0
 * @contact "jisamchan@outlook.com"
 * @date 08/04/2025
 */
@Slf4j
@Component
public class UserBlackListener {

    @Autowired
    private WebSocketService webSocketService;

    @Autowired
    private UserCache userCache;

    @Autowired
    private UserDao userDao;

    /**
     * 刷新Redis缓存
     *
     * @param event 用户拉黑事件
     */
    @Async
    @EventListener(classes = UserBlackEvent.class)
    public void refreshRedis(UserBlackEvent event) {
        userCache.evictBlackMap();
        userCache.remove(event.getUser().getId());
    }

    /**
     * 发送拉黑推送消息
     *
     * @param event 用户拉黑事件
     */
    @Async
    @EventListener(classes = UserBlackEvent.class)
    public void sendPush(UserBlackEvent event) {
        webSocketService.sendToAllOnline(WebSocketBuilder.buildBlack(event.getUser()), event.getUser().getId());
    }

    /**
     * 修改用户状态
     *
     * @param event 用户拉黑事件
     */
    @Async
    @EventListener(classes = UserBlackEvent.class)
    public void changeUserStatus(UserBlackEvent event) {
        userDao.invalidUid(event.getUser().getId());
    }
}
